package com.chenchao.collection.properties;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/5 15:53
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.collection.properties.Test03.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 读写配置文件
 */
public class Test03 {
    public static final String URL ="myjava01/src/com/chenchao/collection/properties/properties.txt";
    public static void main(String[] args) {
        /*即使存两次相同元素会覆盖*/
        store();
        store();
        load();
    }

    private static void load() {
        Properties properties = new Properties();
        /*创建字符输入流*/
        try (FileReader fileReader = new FileReader(URL)) {
            properties.load(fileReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Set<String> strings = properties.stringPropertyNames();
        for (String string : strings) {
            System.out.println(string+":"+properties.getProperty(string));
        }
    }

    private static void store() {
        Properties properties = new Properties();
        properties.setProperty("key1", "value1");
        properties.setProperty("key2", "value2");
        properties.setProperty("key3", "value3");
        properties.setProperty("key4", "value4");
        /*创建字符输出流*/
        try (FileWriter fileWriter = new FileWriter(URL)) {
            properties.store(fileWriter, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
